import 'package:auto_route/auto_route.dart';
import 'package:casdon/app/config/theme/theme_extention.dart';
import 'package:casdon/common/widget/common_app_bar.dart';
import 'package:casdon/common/widget/common_loading_widget.dart';
import 'package:casdon/modules/recipe/data/model/recipe_module_content_model.dart';

import 'package:casdon/modules/recipe/providers/recipe_provider.dart';
import 'package:casdon/modules/recipe/ui/widgets/Recipe_card_item.dart';
import 'package:casdon/auto_router.dart';

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

@RoutePage()
class RecipeStyle1ListScreen extends ConsumerStatefulWidget {
  final String modelId;
  final String title;

  const RecipeStyle1ListScreen({
    super.key,
    required this.modelId,
    required this.title,
  });

  @override
  ConsumerState<RecipeStyle1ListScreen> createState() =>
      _RecipeStyle1ListState();
}

class _RecipeStyle1ListState extends ConsumerState<RecipeStyle1ListScreen> {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    final contentState = ref.watch(
      recipeModuleContentAsyncProvider(widget.modelId),
    );
    final contentNotifier = ref.watch(
      recipeModuleContentAsyncProvider(widget.modelId).notifier,
    );

    return Scaffold(
      backgroundColor: context.colorScheme.surface,
      appBar: CommonAppBar(title: widget.title),
      body: NotificationListener<ScrollNotification>(
        onNotification: (notification) {
          if (notification is ScrollEndNotification &&
              notification.metrics.pixels >=
                  notification.metrics.maxScrollExtent - 50) {
            contentNotifier.loadMore();
          }
          return false;
        },
        child: RefreshIndicator(
          onRefresh: () async {
            await contentNotifier.refresh();
          },
          child: CustomScrollView(
            slivers: [
              SliverToBoxAdapter(child: SizedBox(height: 12.h)),
              contentState.when(
                loading: () => _buildSliverLoading(),
                error: (e, _) => _buildSliverError(''),
                data: (data) {
                  final items = data.data;
                  if (items.isEmpty) {
                    return _buildSliverEmpty('暂无数据');
                  }
                  return SliverPadding(
                    padding: EdgeInsets.only(left: 12.w, right: 12.w),
                    sliver: SliverGrid(
                      delegate: SliverChildBuilderDelegate((context, index) {
                        return GestureDetector(
                          onTap: () => _handleItemClick(
                            items[index],
                            context,
                          ), // 点击事件写在外面
                          child: RecipeCardItem(item: items[index]), // UI 独立封装
                        );
                      }, childCount: items.length),
                      gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
                        maxCrossAxisExtent: 200.w,
                        mainAxisSpacing: 12.w,
                        crossAxisSpacing: 12.w,
                        mainAxisExtent: 138.h,
                      ),
                    ),
                  );
                },
              ),
              SliverToBoxAdapter(child: SizedBox(height: 12.h)),
            ],
          ),
        ),
      ),
    );
  }

  // ========= 通用状态 Sliver =========
  SliverToBoxAdapter _buildSliverLoading() => const SliverToBoxAdapter(
    child: Padding(
      padding: EdgeInsets.symmetric(vertical: 40),
      child: Center(child: CommonLoadingWidget()),
    ),
  );

  SliverToBoxAdapter _buildSliverError(String message) => SliverToBoxAdapter(
    child: Padding(
      padding: EdgeInsets.symmetric(vertical: 40),
      child: Center(child: Text(message)),
    ),
  );

  SliverToBoxAdapter _buildSliverEmpty(String message) => SliverToBoxAdapter(
    child: Padding(
      padding: EdgeInsets.symmetric(vertical: 40),
      child: Center(
        child: Text(
          message,
          style: TextStyle(fontSize: 14.r, color: Colors.grey),
        ),
      ),
    ),
  );

  void _handleItemClick(RecipeModuleContentModel item, BuildContext context) {
    RecipeDetailRoute(
      recipeId: item.recipeId,
      title: item.title,
      isSmart: item.isSmart,
    ).push(context);
  }
}
